<!-- 客户信息管理 -->
<template>
    <div >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="客户名称">
                            <!-- <a-select v-model="customerName" placeholder="请选择" @change="getData" allow-clear>
                                <a-select-option v-for="item in customerList" :key="item.id" :value="item.customerName">{{item.customerName}}</a-select-option>
                            </a-select> -->
                            <a-input v-model="customerName" placeholder="请输入客户名称" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="社会信用代码">
                            <a-input v-model="socialCode" placeholder="请输入统一社会信用代码" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="所属公司">
                            <!-- <a-select v-model="companyId" placeholder="请选择" @change="getData" allow-clear>
                                <a-select-option v-for="item in companyList" :key="item.id" :value="item.id">{{item.companyName}}</a-select-option>
                            </a-select> -->
                            <a-input v-model="companyName" placeholder="请输入所属公司" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="支付账户">
                            <a-select v-model="accountStatus" placeholder="请选择" @change="getData" allow-clear>
                                <a-select-option v-for="item in sourceList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="状态">
                            <a-select v-model="state" placeholder="请选择" @change="getData" allow-clear>
                                <a-select-option v-for="item in statusList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='16' :sm='24'>
                        <a-form-item label="创建时间">
                            <a-range-picker :show-time="false" format="YYYY-MM-DD" @change="onDateChange" allow-clear/>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button type='primary' @click="getData">查询</a-button>
                            <a-button style="margin-left: 20px" type='' @click="add">添加业务</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  

        <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ total: total ,showSizeChanger: true,pageSize: size,}" size="small" :scroll="{ x: 1200, }">
            <div slot="serviceRate" slot-scope="serviceRate">
                <div>{{serviceRate}}%</div>
            </div>
            <div slot="accountStatus" slot-scope="accountStatus">
                <div v-for="(item,i) in sourceList" :key="item.id">
                    <a-tag v-if="item.id == accountStatus" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="contractStatus" slot-scope="contractStatus">
                <div v-for="(item,i) in hasAuditList" :key="item.id">
                    <a-tag v-if="item.id == contractStatus" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="state" slot-scope="state">
                <a-badge :status="state | statusTypeFilter" :text="state | statusFilter" />
            </div>
            <div slot="operation" slot-scope="text,record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="detail(record)">详情</a-button>
                    <a-popconfirm
                        title="是否启用当前客户业务?"
                        ok-text="是"
                        cancel-text="否"
                        @confirm="updateState(record,1)"
                        v-if="record.state == 0"
                    >
                        <a-button type="link">启用</a-button>
                    </a-popconfirm>
                    <a-button v-else type="link" @click="close(record)">停用</a-button>
                </div>
            </div>
        </a-table>

        <a-modal 
            v-model="visible" 
            title="添加业务"
            @ok="handleOk" 
            @cancel="visible = false">
            <div>
                <a-form-model :model="info" ref="ruleForm" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
                    <a-form-model-item label="客户名称" prop="customerId">
                        <a-select v-model="info.customerId" placeholder="请选择" @change="selAddCustomer">
                            <a-select-option v-for="item in customerList" :key="item.id" :value="item.id">{{item.customerName}}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="统一社会信用代码">
                        <a-input v-model="info.socialCode" :disabled="true" allow-clear placeholder="请选择客户信息" />
                    </a-form-model-item>
                    <a-form-model-item label="所属公司" prop="companyId">
                        <a-select v-model="info.companyId" placeholder="请选择">
                            <a-select-option v-for="item in companyList" :key="item.id" :value="item.id">{{item.companyName}}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { queryCustomerList , createCustomerBusiness , queryCustomerBusinessList , updateCustomerBusinessState } from '@/api/services/customer';
import { queryMyCompany } from '@/api/services/company';
export default {
    data () {
        return {
            isload: false,
            dataList: [],
            startTime: '', 
            endTime: '',
            customerName: '', // 客户名称
            socialCode: '', // 统一社会信用代码
            companyId: '', // 所属公司
            companyName: '', // 所属公司
            companyList: [],
            page: 1,
            size: 10,
            total: 0,
            accountStatus: undefined,
            sourceList: [
                { id: 0, name: '未设置'},
                { id: 1, name: '已设置'}
            ],
            hasAuditList: [
                { id: 0, name: '待上传'},
                { id: 1, name: '已上传'}
            ],
            state: undefined,
            statusList: [
                { id: 0, name: '已停用'},
                { id: 1, name: '使用中'}
            ],
            columns,
            form: this.$form.createForm(this.info),
            info: {
                customerId: undefined, // 客户ID
                socialCode: '', // 社会信用代码
                companyId: undefined, // 所属公司ID
            },
            visible: false,
            active: 1,
            customerList: [], // 客户列表
            rules: {
                customerId: [
                    { required: true, message: '请选择客户信息', trigger: 'blur' },
                ],
                companyId: [{ required: true, message: '请选择所属公司', trigger: 'blur' }],
            },
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
        };
    },
    async created(){
        try {
            await this.getUserCompany();
            await this.getUserCustomer();
            this.getData();
        } catch (error) {
            this.$notification['error']({
                message: '温馨提示',
                description: error,
                duration: 8
            })
        }
    },
    methods: {
        // 日期筛选
        onDateChange(date,dateStr){
            console.log(date,dateStr)
            if(date.length > 0){
                this.startTime = date[0].format('YYYY-MM-DD')
                this.endTime = date[1].format('YYYY-MM-DD')
            }else{
                this.startTime = ''
                this.endTime = ''
            }
            this.getData()
        },
        // 获取账户列表数据
        getData(){
            let _this = this
            _this.isload = true;
            const params = {
                'startTime': _this.startTime,
                'endTime': _this.endTime,
                'customerName': _this.customerName,
                'socialCode': _this.socialCode,
                'companyName': _this.companyName,
                'accountStatus': _this.accountStatus,
                'state': _this.state,
                'pageIndex': _this.page,
                'pageSize': _this.size,
            }
            queryCustomerBusinessList(params)
            .then(res=>{
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data;
                    _this.total = res.totalCount;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 添加客户
        add(){
            this.info.customerName = ''
            this.info.socialCode = ''
            this.info.contactName = ''
            this.info.contactPhone = ''
            this.info.password = ''
            this.visible = true
        },
        // 选择客户业务，自动填充社会信用代码
        selAddCustomer(id){
            this.info.socialCode = this.customerList.find(item => item.id == id).socialCode
        },
        handleOk(){
            let _this = this
            _this.$refs.ruleForm.validate(valid => {
                if(valid){
                    const params = {
                        'customerId': _this.info.customerId,
                        'companyId': _this.info.companyId,
                    }
                    createCustomerBusiness(params)
                    .then(res=>{
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: '添加成功',
                                duration: 8
                            })
                            _this.visible = false;
                            _this.getData()
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        // 获取当前用户下面的劳务公司
        getUserCompany(){
            let _this = this
            return new Promise((resolve,reject) => {
                const params = {
                }
                queryMyCompany(params)
                .then(res=>{
                    if(res.success){
                        _this.companyList = res.data;
                        resolve();
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 获取当前用户下的客户列表
        getUserCustomer(){
            let _this = this
            return new Promise((resolve,reject) => {
                const params = {
                    'pageIndex': 1,
                    'pageSize': 99
                }
                queryCustomerList(params)
                .then(res=>{
                    if(res.success){
                        _this.customerList = res.data;
                        resolve();
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 关闭客户业务
        close(item){
            let _this = this
            _this.$confirm({
                title: '温馨提示',
                content: '停用后，该业务关联的客户将不可发布对应所属公司的项目以及上传结算单',
                okText: '确认结束',
                onOk() {
                    _this.updateState(item,0)
                },
                onCancel() {},
            });
        },
        // 修改业务状态
        updateState(item,state){
            let _this = this
            const params = {
                'state': state,
                'customerBusinessId': item.id
            }
            updateCustomerBusinessState(params)
            .then(res=>{
                if(res.success){
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: state == 1 ? '开启成功' : '关闭成功',
                        duration: 8
                    })
                    _this.getData()
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 详情
        detail(item){
            this.$router.push({ path: '/servicesCustomer/businessDetail', query: { 'business': JSON.stringify(item)}});
        },
    }
}

</script>
<style scoped>

</style>